package com.xingkeduo.business.order.remote;

import com.alibaba.fastjson.JSON;
import com.xingkeduo.utils.DateTimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.TimeUnit;
@Service
@Slf4j
public class WaitLineRemoteServiceImpl implements WaitLineRemoteService {

    private String waitLine = "waitLine:";

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 根据店铺id，获取当天排队号
     * @param storeId
     * @return
     */
    public String getWaitLineNo(String storeId,LocalDateTime  appointmentStartTime) {
        if(appointmentStartTime==null || storeId ==null){
            return "";
        }

        try {
            String key = waitLine + storeId+"_createdTime_"+ DateTimeUtils.yyyy_MM_dd(appointmentStartTime);
            log.info("getWaitLineNo key:{}", JSON.toJSONString(key));

            //判断redis中key是否存在，存在+1
            if(redisTemplate.hasKey(key)){
                String string =String.valueOf(redisTemplate.opsForValue().get(key));
                log.info("存在排队号:{}",string);

                string=string.replace("\"","");
                if("249".equals(string)){
                    string="250";
                }
                setValue(key,appointmentStartTime,Integer.valueOf(string));

                return String.valueOf(incr(key));
            }
            setValue(key,appointmentStartTime,180);
        } catch (Exception e) {
            log.error("生成排队号报错:{}", e);
        }
        return String.valueOf(180);
    }

    /**
     * @description: value缓存到redis
     * @author: ch
     * @Param [key, appointmentStartTime, num]
     * @return void
     * @date: 2019-06-20 10:32
     **/
    public void setValue(String key,LocalDateTime  appointmentStartTime,int num){
        //设置redis中key及过期时间 当天24时过期
        LocalDateTime midnight = appointmentStartTime.plusDays(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
        long seconds = ChronoUnit.SECONDS.between(LocalDateTime.now(), midnight);
        redisTemplate.opsForValue().set(key,num,seconds, TimeUnit.SECONDS);
    }


    /**
     * redis incr
     * @param key
     * @return
     */
    private int incr(String key){
        ValueOperations<String, Object> operations = redisTemplate.opsForValue();
//        redisTemplate.setKeySerializer(new StringRedisSerializer());
//        redisTemplate.setValueSerializer(new StringRedisSerializer());
        return Math.toIntExact(operations.increment(key));
    }


}
